<template>
  <div class="contents">
    <div class="contitem">
      <div
        v-for="item in workshopConfig1"
        :key="item.id"
        ref="desk1"
        :class="['item', { 'type-1': item.type === 1, 'type-2': item.type === 2 }]"
        :data-id="item.id"
      >
        <div class="title">{{ item.name }}</div>
        <div v-if="item.type === 3" class="maskicon"></div>
        <!-- <div v-if="item.type === 3" class="callicon"></div> -->
      </div>
    </div>
    <div class="contitem carLine">
      <CarTractionMove ref="tractionRef1" />
    </div>
    <div class="contitem">
      <div
        v-for="item in workshopConfig3"
        :key="item.id"
        ref="desk3"
        :class="['item', { 'type-1': item.type === 1, 'type-2': item.type === 2 }]"
        :data-id="item.id"
      >
        <div class="title">{{ item.name }}</div>
      </div>
    </div>
    <div class="contitem">
      <div
        v-for="item in workshopConfig4"
        :key="item.id"
        ref="desk4"
        :class="['item', { 'type-1': item.type === 1, 'type-2': item.type === 2 }]"
        :data-id="item.id"
      >
        <div class="title">{{ item.name }}</div>
      </div>
    </div>
    <div class="contitem carLine">
      <CarTractionMove ref="tractionRef2" />
    </div>
    <div class="contitem">
      <div
        v-for="item in workshopConfig6"
        :key="item.id"
        ref="desk6"
        :class="['item', { 'type-1': item.type === 1, 'type-2': item.type === 2 }]"
        :data-id="item.id"
      >
        <div class="title">{{ item.name }}</div>
        <div v-if="item.type === 3" class="maskiconlast"></div>
        <!-- <div v-if="item.type === 3" class="calliconlast"></div> -->
      </div>
    </div>
  </div>
  <div class="jsplumb-wrapper">
    <CarMoveJsPlumb ref="carMoveRef" :desk="allDesks" />
  </div>
</template>

<script setup>
import {computed, nextTick, onMounted, reactive, ref} from 'vue';
import CarMoveJsPlumb from './car_move_jsplumb.vue';
import CarTractionMove from './car_traction_move.vue';
import {initWebSocket} from '@/utils/websocket';
import {getWorkAllCar} from '@/api/dashboard/workCar';

const getRem = (baseSize = 10, designWidth = 1920) => {
  const scale = document.documentElement.clientWidth / designWidth;
  return baseSize * Math.min(scale, 2);
};
const props = defineProps({
  message: String
});
const route = useRoute();
const carInfo = reactive({
  currentIndex: 0,
  endId: null,
  id: 'dry-1', //车间id
  isMoving: false,
  progress: 90,
  startId: null,
  status: 1,
  step: null,
  vehicleId: '' //小车id
});

const workshopConfig1 = [
  // 第1列
  { type: 1, id: 'sand-2', name: '喷砂间2' },
  { type: 3, id: 'sand-1', name: '喷砂间1' },
  { type: 1, id: 'wood-2', name: '木骨间2' },
  { type: 1, id: 'wood-1', name: '木骨间1' },
  { type: 1, id: 'room-9', name: '腻子间9' },
  { type: 3, id: 'room-8', name: '腻子间8' },
  { type: 2, id: 'outline', name: '出车线' },
  { type: 1, id: 'room-7', name: '腻子间7' },
  { type: 1, id: 'room-6', name: '腻子间6' },
  { type: 1, id: 'room-5', name: '腻子间5' },
  { type: 1, id: 'room-4', name: '腻子间4' },
  { type: 1, id: 'room-3', name: '腻子间3' },
  { type: 1, id: 'room-2', name: '腻子间2' },
  { type: 1, id: 'room-1', name: '腻子间1' }
];

const workshopConfig3 = [
  { type: 1, id: 'weld-22', name: '补焊间2-2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'weld-12', name: '补焊间1-2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-122', name: '准备台位12-2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-112', name: '准备台位11-2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-102', name: '准备台位10-2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-92', name: '准备台位09-2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-82', name: '准备台位08-2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 2, id: 'passline2', name: '通过线1', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-72', name: '准备台位07-2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-62', name: '准备台位06-2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-52', name: '准备台位05-2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-42', name: '准备台位04-2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-32', name: '准备台位03-2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-22', name: '准备台位02-2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-12', name: '准备台位01-2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` }
];

const workshopConfig4 = [
  // 第4列
  { type: 1, id: 'weld-21', name: '补焊间2-1', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'weld-11', name: '补焊间1-1', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-121', name: '准备台位12-1 ', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-111', name: '准备台位11-1', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-101', name: '准备台位10-1', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-91', name: '准备台位09-1', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-81', name: '准备台位08-1', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 2, id: 'passline1', name: '通过线2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-71', name: '准备台位07-1', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-61', name: '准备台位06-1', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-51', name: '准备台位05-1', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-41', name: '准备台位04-1', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-31', name: '准备台位03-1', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-21', name: '准备台位02-1', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'surface-11', name: '准备台位01-1', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` }
];

const workshopConfig6 = [
  // 第6列
  { type: 1, id: 'ny-paint-1', name: '降噪间1', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'ny-paint-2', name: '降噪间2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'dry-1', name: '烘干间1', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'dry-2', name: '烘干间2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'putty-bake', name: '底漆间', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'mid-paint', name: '中涂间', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'mq-1', name: '面漆间1', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'mq-2', name: '面漆间2', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'dry-3', name: '烘干间3', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 2, id: 'inline1', name: '进车线', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 3, id: 'mq-3', name: '面漆间3', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 3, id: 'mq-4', name: '面漆间4', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'dry-4', name: '烘干间4', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 2, id: 'inline2', name: '进车线', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` },
  { type: 1, id: 'dry-5', name: '烘干间5', vehicleId: `VH${Math.floor(1000 + Math.random() * 9000)}` }
];

const carMoveRef = ref(null);
const desk1 = ref([]);
const desk3 = ref([]);
const desk4 = ref([]);
const desk6 = ref([]);

// 合并所有工位引用
const allDesks = computed(() => {
  return [...desk1.value, ...desk3.value, ...desk4.value, ...desk6.value];
});

const tractionRef1 = ref(null);
const tractionRef2 = ref(null);

const updateTctPositions = () => {
  // Remove old car refs since we're using canvas now
};
const WorkAllCarArr = ref([]);
const updateWorkCar = async () => {
  const res = await getWorkAllCar();

  if (res.code !== 200) {
    return;
  }

  WorkAllCarArr.value = res.data;
  initializeCars({
    'vehicleInfos': WorkAllCarArr.value
  });
};

const updateWorkshops = (previousData, data) => {
  // 确保 data 是数组
  if (!Array.isArray(data)) {
    console.error('Data is not an array:', data);
    return;
  }

  // 更新上一个工位状态
  previousData.forEach((item) => {
    allDesks.value.forEach((car) => {
      if (car.dataset.id === item.id) {
        const elem = car;
        // elem.style.background = '#4087d8'
      }
    });
  });

  data.forEach((item) => {
    allDesks.value.forEach((car) => {
      if (car.dataset.id === item.id) {
        const elem = car;
        // 更新状态和进度
        const progress = item.progress || 0;
        const statusClass = `status-${item.status} item`;
        // elem.className = elem.className.replace(/status-\d/, '') + ` ${statusClass}`;
        // 更新背景渐变
        // const baseColor = getStatusColor(item.status);
        // const progressColor = getProgressColor(progress);
        // elem.style.background = `linear-gradient(to right, ${progressColor} ${progress}%, ${baseColor} ${progress}%)`;
      }
    });
  });
};

// 状态颜色计算
const getStatusColor = (status) => {
  // 未开始 进行中 故障 完工
  const colors = {
    0: '#4087d8', // 未开始
    1: '#4087d8', // 进行中
    2: '#ff0000', // 故障
    3: '#00ff00' // 完工
  };
  return colors[status] || colors[0];
};

// 进度颜色计算
const getProgressColor = (percent) => {
  if (percent < 30) return '#84436b';
  if (percent < 70) return '#e6e9a3';
  return '#6fe0cd';
};

// 初始化小车数据
const initializeCars = (data, isAdd = false) => {
  console.log('Initializing cars with data:', data);
  // 等待一段时间确保工位元素完全渲染和定位
  nextTick(() => {
    const carsData = data.vehicleInfos
      .filter((item) => item.vehicleId)
      .map((item) => ({
        id: item.vehicleId,
        wbs: item.wbs,
        progress: item.progress || 0,
        wholeProgress: item.wholeProgress || 0,
        type: item.type, //1车头图片 2车头文字
        startTime: item.startTime,
        position: {
          deskId: item.tableId,
          deskName: item.idName,
          // nextdeskId: item.nextdeskid,
          nextdeskName: item.nextdeskName
        }
      }));
    if (carMoveRef.value) {
      carMoveRef.value.initializeCars(carsData, isAdd, initializeCarsCallback);

      // 初始化完成后立即开始移动，测试是这样的，后续生产需要通过ws进行通讯，不需要立即开始移动
      // setTimeout(() => {
      //   startTestSequence();
      // }, 1000);
    } else {
      console.error('carMoveRef is not initialized');
    }
  });
};

/**
 * 初始化车辆状态回调函数
 *
 * 该函数用于初始化或更新单个车辆的状态信息，将传入的车辆数据同步到全局的车辆状态对象中。
 *
 * @param {Object} carData - 车辆数据对象
 * @param {string} carData.id - 车辆的唯一标识符
 * @param {number} [carData.currentIndex=0] - 车辆的当前位置索引（可选，默认为0）
 * @param {boolean} [carData.isMoving=false] - 车辆是否正在移动的标志（可选，默认为false）
 * @returns {void} 无返回值，直接修改全局的carStates对象
 */
const initializeCarsCallback = (carData) => {
  // 更新全局车辆状态对象，使用传入值或默认值初始化指定车辆的状态
  carStates.value[carData.id] = {
    currentIndex: carData.currentIndex || 0,
    isMoving: carData.isMoving || false
  };
};

// 初始化牵车
// todo 后面需要调用接口获取牵车台位置
const initializeTractionCars = () => {

  // 初始化第一条轨道的牵车
  tractionRef1.value.initializeCars(0, [{ id: 'traction1-1', name: '移车台1', position: 'wood-1'}]);

  // 初始化第二条轨道的牵车
  tractionRef2.value.initializeCars(0, [
    { id: 'traction2-1', name: '移车台2', position: 'dry-2' },
    { id: 'traction2-2', name: '移车台3', position: 'dry-4' }
  ]);
};

// 测试移动牵车
const testTractionMovement = async () => {
  try {
    // 移动第一条轨道的牵车
    await tractionRef1.value.moveCar(0, 'traction1-1', 'room-1'); // 移动到1号腻子间
    await tractionRef1.value.moveCar(0, 'traction1-2', 'room-5'); // 移动到5号腻子间

    // 等待一段时间
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // 移动第二条轨道的牵车
    await tractionRef2.value.moveCar(0, 'traction2-1', 'surface-1'); // 移动到表面准备台位1
    await tractionRef2.value.moveCar(0, 'traction2-2', 'surface-5'); // 移动到表面准备台位5

    // 再次移动第一条轨道的牵车
    await new Promise((resolve) => setTimeout(resolve, 1000));
    await tractionRef1.value.moveCar(0, 'traction1-1', 'room-3'); // 移动到3号腻子间
    await tractionRef1.value.moveCar(0, 'traction1-2', 'room-7'); // 移动到7号腻子间

    // 添加新的测试移动
    await new Promise((resolve) => setTimeout(resolve, 1000));
    await tractionRef1.value.moveCar(0, 'traction1-1', 'room-9'); // 移动到9号腻子间
    await tractionRef1.value.moveCar(0, 'traction1-2', 'room-2'); // 移动到2号腻子间

    await new Promise((resolve) => setTimeout(resolve, 1000));
    await tractionRef2.value.moveCar(0, 'traction2-1', 'surface-3'); // 移动到表面准备台位3
    await tractionRef2.value.moveCar(0, 'traction2-2', 'surface-7'); // 移动到表面准备台位7

    await new Promise((resolve) => setTimeout(resolve, 1000));
    await tractionRef1.value.moveCar(0, 'traction1-1', 'room-4'); // 移动到4号腻子间
    await tractionRef1.value.moveCar(0, 'traction1-2', 'room-6'); // 移动到6号腻子间

    await new Promise((resolve) => setTimeout(resolve, 1000));
    await tractionRef2.value.moveCar(0, 'traction2-1', 'surface-2'); // 移动到表面准备台位2
    await tractionRef2.value.moveCar(0, 'traction2-2', 'surface-4'); // 移动到表面准备台位4

    await new Promise((resolve) => setTimeout(resolve, 1000));
    await tractionRef1.value.moveCar(0, 'traction1-1', 'room-8'); // 移动到8号腻子间
    await tractionRef1.value.moveCar(0, 'traction1-2', 'room-1'); // 移动到1号腻子间
  } catch (error) {
    console.error('Error during traction movement:', error);
  }
};

// 测试序列数据 - 只保留VH1001的路线
const testSequences = {
  '0011112': [
    // // 移车台位置
    { id: 'surface-14', vehicleId: '0011112', status: 1, progress: 45, isTraction: true, isCarryingCar: false }
    // 工位位置，移车台移动到工位
    // { id: 'dry-1', vehicleId: '0011112', status: 1, progress: 90 }
    // // 移车台位置，小车移动到移车台
    // { id: 'dry-1', vehicleId: '0011112', status: 1, progress: 90, isTraction: true, isCarryingCar: false },
    // // 移车台位置，移车台带着小车移动到指定工位的牵车轨道位置
    // { id: 'surface-14', vehicleId: '0011112', status: 1, progress: 45, isTraction: true, isCarryingCar: true }
    // 工位位置，移车台移动到工位
    // { id: 'surface-14', vehicleId: '0011112', status: 1, progress: 45, isTraction: false, isCarryingCar: true }
    // { id: 'dry-4', vehicleId: 'VH1001', status: 1, progress: 75 },
    // { id: 'pass-line-1', vehicleId: 'VH1001', status: 1, progress: 60 },
    // { id: 'room-5', vehicleId: 'VH1001', status: 1, progress: 30 }
  ]
  // '0011112': [
  //   // // 移车台位置
  //   { id: 'weld-3', vehicleId: '0011112', status: 1, progress: 45, isTraction: true, isCarryingCar: false },
  //   // 工位位置，移车台移动到工位
  //   { id: 'surface-2', vehicleId: '0011112', status: 1, progress: 90 },
  //   // 移车台位置，小车移动到移车台
  //   { id: 'surface-2', vehicleId: '0011112', status: 1, progress: 90, isTraction: true, isCarryingCar: false },

  // ]
  // '0011112': [
  //   //   // 工位位置，移车台移动到工位
  //   { id: 'dry-3', vehicleId: '0011112', status: 1, progress: 90 },
  //   { id: 'dry-3', vehicleId: '0011112', status: 1, progress: 90, isTraction: true, isCarryingCar: false },
  //   { id: 'BMZB1', vehicleId: '0011112', status: 1, progress: 90, isTraction: false, isCarryingCar: true }
  // ]
};

// 记录每个车的当前位置和状态
const carStates = ref({
  // car1: { currentIndex: 0, isMoving: false }
});

// 检查位置是否被占用
const isPositionOccupied = (positionId, currentCarId) => {
  //console.log(7887887,positionId, currentCarId);
  return Object.values(carStates.value).some((state) => {
    const carId = Object.keys(carStates.value).find((key) => carStates.value[key] === state);
    //console.log(888888,carId,currentCarId)
    // 排除当前小车的位置
    if (carId === currentCarId) return false;

    const sequence = testSequences[carId];
    const currentPosition = sequence[state.currentIndex];
    return currentPosition && currentPosition.id === positionId;
  });
};

// 检查路径是否安全
const isPathSafe = (startId, endId, currentCarId) => {
  // 获取所有正在移动的小车
  const movingCars = Object.entries(carStates.value)
    .filter(([carId, state]) => state.isMoving && carId !== currentCarId)
    .map(([carId, state]) => {
      const sequence = testSequences[carId];
      const currentPosition = sequence[state.currentIndex];
      const previousPosition = state.currentIndex > 0 ? sequence[state.currentIndex - 1] : null;
      return {
        carId,
        startId: previousPosition ? previousPosition.id : currentPosition.id,
        endId: currentPosition.id
      };
    });

  // 检查是否有其他小车正在使用相同的路径
  return !movingCars.some((car) => {
    // 检查起点或终点是否相同
    if (car.startId === startId || car.startId === endId || car.endId === startId || car.endId === endId) {
      return true;
    }

    // 检查路径是否交叉
    // 这里我们需要检查两个路径是否共享任何中间点
    // 由于我们的路径是直线移动，我们只需要检查起点和终点
    const isVertical1 = startId.includes('surface') || endId.includes('surface');
    const isVertical2 = car.startId.includes('surface') || car.endId.includes('surface');

    // 如果两个路径都是垂直移动，检查是否在同一列
    if (isVertical1 && isVertical2) {
      const column1 = startId.split('-')[0];
      const column2 = car.startId.split('-')[0];
      return column1 === column2;
    }

    // 如果两个路径都是水平移动，检查是否在同一行
    if (!isVertical1 && !isVertical2) {
      const row1 = startId.split('-')[1];
      const row2 = car.startId.split('-')[1];
      return row1 === row2;
    }

    return false;
  });
};

// 开始测试序列
const startTestSequence = () => {
  console.log('=== startTestSequence ===');
  console.log('Starting test sequence...');
  let hasMoved = false;
  console.log('Car states:', carStates.value);
  console.log('testSequences', testSequences);
  Object.keys(carStates.value).forEach((carId) => {
    const state = carStates.value[carId];
    const sequence = testSequences[carId];
    console.log('Processing car:', carId);
    console.log('Current state:', state);
    console.log('Sequence:', sequence);

    if (state.currentIndex < sequence.length && !state.isMoving) {
      const currentPosition = sequence[state.currentIndex];
      // 获取前一个位置
      const previousPosition = state.currentIndex > 0 ? sequence[state.currentIndex - 1] : null;
      // 如果当前位置是初始位置，则不考虑前一个位置
      // previousPosition = currentPosition.isInitializer || false ? null : previousPosition
      // 获取起点,
      const startId = previousPosition ? previousPosition.id : currentPosition.id;

      console.log('Checking movement conditions:');
      console.log('Current position:', currentPosition);
      console.log('Previous position:', previousPosition);
      console.log('Start ID:', startId);

      // 检查目标位置和路径是否安全
      if (!isPositionOccupied(currentPosition.id, carId) && isPathSafe(startId, currentPosition.id, carId)) {
        console.log(`Moving ${carId} to ${currentPosition.id}`);
        state.isMoving = true;
        hasMoved = true;
        // 获取起点和终点是否为移车台
        const isTractionEnd = currentPosition.isTraction || false;
        const isTractionStart = previousPosition ? previousPosition.isTraction || false : isTractionEnd;
        console.log('isTractionStart', isTractionStart);
        console.log('isTractionEnd', isTractionEnd);
        const moveMessage = {
          carId: currentPosition.vehicleId,
          startId: startId,
          endId: currentPosition.id,
          isCarryingCar: currentPosition.isCarryingCar || false,
          isTractionStart: isTractionStart,
          isTractionEnd: isTractionEnd,
          onComplete: () => {
            if (isTractionStart && isTractionEnd) {
              // 移车台到移车台
              console.log('移车台到移车台,不更新工位状态');
            } else {
              console.log(`Movement completed for ${carId}`);
              // 更新工位状态
              updateWorkshops(previousPosition ? [previousPosition] : [], [currentPosition]);
            }
            state.currentIndex++;
            state.isMoving = false;
          }
        };
        console.log('Sending move message:', moveMessage);
        handleMoveMessage(moveMessage);
      } else {
        console.log(`Path to ${currentPosition.id} is not safe, waiting...`);
      }
    }
  });

  // 检查是否所有车都完成了移动
  const allCarsFinished = Object.values(carStates.value).every(
    (state) => state.currentIndex >= testSequences[Object.keys(carStates.value)[0]].length
  );

  if (!allCarsFinished) {
    // 如果没有任何车移动，增加等待时间
    const delay = hasMoved ? 2000 : 5000;
    console.log(`Scheduling next movement check in ${delay}ms`);
    setTimeout(startTestSequence, delay);
  } else {
    console.log('All cars have completed their routes');
  }
  console.log('=== endTestSequence ===');
};

// 模拟数据测试
// const getVehicleInfo = async () => {
//   try {
//     const response = await getWorkshopVehicleInfo();
//     if (response.code === 200) {
//       return response.data || [];
//     }
//     console.error('Failed to fetch workshop vehicle info:', response.msg);
//     return [];
//   } catch (error) {
//     console.error('Error fetching workshop vehicle info:', error);
//     return [];
//   }
// };

// 处理移动消息
const handleMoveMessage = (message) => {
  console.log('=== startTestSequence handleMoveMessage ===');
  console.log('Handling move message:', message);
  if (carMoveRef.value) {
    console.log('Calling carMoveRef.handleMoveMessage');
    carMoveRef.value.handleMoveMessage(message);
  } else {
    console.error('carMoveRef is not available for movement');
  }
  console.log('=== endTestSequence handleMoveMessage ===');
};

/**
 * 处理WebSocket消息
 * @param {Object} message - 接收到的WebSocket消息对象，包含类型和数据
 * 该函数根据消息类型处理不同的逻辑，主要处理车辆信息和车辆序列信息
 */
const handleWebSocketMessage = (message) => {
  // 标识开始处理WebSocket消息
  console.log('=== startTestSequence handleWebSocketMessage ===');
  // 输出接收到的WebSocket消息内容
  console.log('Received websocket message:', message.data);
  // initializeCars(message.data || [], true);
  // // 根据消息类型处理相应的逻辑
  // if (message.type === 'vehicle_info') {
  //   // 处理车辆信息类型的消息
  //   console.log('Handling vehicle_info message:', message);
  //   // 初始化车辆信息
  //   initializeCars(message.data || [], true);
  // } else if (message.type === 'vehicle_sequences') {
  // 处理车辆序列信息类型的消息
  // console.log('Handling vehicle_sequences message:', message);
  // 遍历车辆序列信息
  message.data.vehicleSequences.forEach((item) => {
    // 获取或初始化车辆对应的测试序列
    const sequence = testSequences[item.vehicleId] || [];
    // 将序列信息添加到对应车辆的测试序列中
    item.sequenceList.forEach((item2) => {
      sequence.push(item2);
    });
    testSequences[item.vehicleId] = sequence;
    // 输出更新后的测试序列信息
  });

  let res1 = message.data.vehicleSequences[0].sequenceList[0].status;
  // console.log(res1, 'res1');
  const carDom = document.getElementById('car-0011112');
  // console.log(carDom, 'car-0011112');
  if (res1 == 1) {
    // carDom.style.display = 'block';
    carDom.style.transform = 'translateX(0)';
    carDom.style.opacity = '1';
  } else {
    // carDom.style.display = 'none';
    // carDom.style.transition = 'transform 8s ease, opacity 100s ease';
    carDom.style.transform = 'translateX(100%)';
    carDom.style.opacity = '0';
  }

  // 启动测试序列
  // startTestSequence();
  // }
};

// 修改 onMounted
onMounted(async () => {
  getRem();
  // 确保所有refs都已经挂载
  nextTick(() => {
    // 初始化小车位置
    // await getVehicleInfo()
    // console.log(await getVehicleInfo(),11111111);

    /**
     * 轨道车辆生产线的工位状态数据对象
     *
     * @property {number} currentIndex - 当前工位在生产线中的索引位置
     * @property {string} startTime - 车辆进入该工位的开始时间，格式'YYYY-MM-DD HH:mm'
     * @property {string} wbs - 工位的项目号
     * @property {string} id - 当前工位的唯一标识符
     * @property {string} idName - 当前工位的显示名称
     * @property {string} nextdeskId - 下一个工位的ID
     * @property {string} nextdeskName - 下一个工位的名称
     * @property {boolean} isMoving - 标识车辆是否正在移动中
     * @property {number} progress - 当前工位作业进度百分比(0-100)
     * @property {string} vehicleId - 当前工位处理的车辆ID
     * @property {number} status - 工位状态码(1表示正常工作中)
     * @property {string} type - 车辆类型('cz'表示某种特定类型)
     */

    updateWorkCar();

    // 172.20.10.4:8080
    const protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
    initWebSocket(protocol + '192.168.1.196:8080' + '/resource/websocket', handleWebSocketMessage);
    // 初始化牵车
    initializeTractionCars();

    // 设置移车台引用
    if (carMoveRef.value) {
      carMoveRef.value.setTractionRef(tractionRef1.value);
      carMoveRef.value.setTractionRef(tractionRef2.value);
    }

    // 测试牵车移动
    // setTimeout(() => {
    // testTractionMovement()
    // }, 2000)
  });
});
</script>

<style scoped>
.type-2 {
  background: none !important;
  border: none !important;
}
.contents {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-around;
  position: relative;
  z-index: 0;
}

.jsplumb-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.contitem {
  height: 100%;
  width: calc(100% / 6.2);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item {
  width: 100%;
  height: calc(100% / 17);
  background-image: url('@/assets/cjbj.png');
  background-size: 100% 100%;
  background-position: center;
  background-repeat: no-repeat;
  border-radius: 0.5rem;
  border: 0.1rem solid #315788;
  margin-top: 0.3rem;
  transition: background 0.3s ease;
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  text-align: center;
  position: relative;
  /* font-size: 1.5rem; */
}

.title {
  color: #fff;
  font-size: 1.2rem;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.maskiconlast,
.maskicon {
  width: 1.5rem;
  height: 1.5rem;
  position: absolute;
  top: 0rem;
  right: -1.5rem;
  background-image: url('@/assets/lsicon.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  border: 1px solid rgba(255, 255, 255, 0.5);
  border-radius: 10%;
  z-index: 9999;
}
.maskiconlast {
  left: -1.5rem;
}
.calliconlast,
.callicon {
  width: 1.5rem;
  height: 1.5rem;
  position: absolute;
  bottom: 0rem;
  right: -1.5rem;
  background-image: url('@/assets/hjicon.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  border: 1px solid rgba(255, 255, 255, 0.5);
  border-radius: 10%;
}
.calliconlast {
  left: -1.5rem;
}
.carLine {
  height: 100%;
  /* background: rgba(9, 182, 106, 0.3); */
  margin-top: 3px;
  position: relative;
  /* height: calc(100% / 17 * 15 + 41px); */
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

/* 状态颜色 */
.status-0 {
  background: linear-gradient(to right, #f0f0f0 0%, #f0f0f0 100%);
}

.status-1 {
  background: linear-gradient(to right, #b3e6ff 0%, #b3e6ff 100%);
}

.status-2 {
  background: linear-gradient(to right, #ffb3b3 0%, #ffb3b3 100%);
}

.status-3 {
  background: linear-gradient(to right, #c3ffb9 0%, #c3ffb9 100%);
}
</style>
